package com.kuangstudy.service.prize;

import com.kuangstudy.constant.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年09月18日
 * @Description 完成抽一等奖、二等奖、三等奖功能
 */
@Service
@Slf4j
public class DrowPrizeKCronService {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    private void initPrize(){
        // 防止重复加入到缓存中
        if (!redisTemplate.hasKey(RedisConstants.USER_DROW_KCRON_SET)) {
            List<String> initDataList = this.initDataList();
            initDataList.forEach(kCron -> redisTemplate.opsForSet().add(RedisConstants.USER_DROW_KCRON_SET, kCron));
        }
    }


    /**
     * 模拟用户抽取 K币
     * @param userId 用户id
     * @return
     */
    public String drowKCorn(Long userId){
        String result = null;
        if (!redisTemplate.hasKey(RedisConstants.USER_DROW_KCRON_SET)) {
            log.error("redis中【user:drow:kcron:set】不存在...");
        }
        String resultStr = (String)redisTemplate.opsForSet().randomMember(RedisConstants.USER_DROW_KCRON_SET);
        if (StringUtils.isNotBlank(resultStr)){
            int index = resultStr.indexOf("#");
            int cron = Integer.valueOf(resultStr.substring(0, index));
            if (cron == 0){
                result = "谢谢你的参与";
            }else if (cron == 10){
                result = "获取到10个K币";
            }else if (cron == 50){
                return "获取到50个K币";
            }else if (cron == 100){
                result = "获取到100个K币";
            }else {
                result = "谢谢你的参与";
            }

            if (cron > 0) {
                // todo 抽取成功以后同步到数据库db中
            }
            return result;
        }

        return "谢谢你的参与";
    }


    /**
     * 初始化K币奖品信息
     * @return
     */
    private List<String> initDataList() {
        List<String> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            dataList.add("100#" + i);
        }
        for (int i = 0; i < 20; i++) {
            dataList.add("50#" + i);
        }
        for (int i = 0; i < 60; i++) {
            dataList.add("10#" + i);
        }
        for (int i = 0; i < 10; i++) {
            dataList.add("0#" + i);
        }
        return dataList;
    }



}
